package com.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.model.Student;
import com.servicesImpl.StudentServicesImpl;

/**
 * Servlet implementation class StudentRegisterController
 */
public class StudentRegisterController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	int i = 0;
	Student student = null;
	StudentServicesImpl studentServicesImpl = null;
	List<Student> students = null;	

	/**
	 * Default constructor. 
	 */
	public StudentRegisterController() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("In studentRegisterPost");
		String action=request.getParameter("action");
		System.out.println(action);
		if(action.equalsIgnoreCase("save"))	{
			student = new Student();
			studentServicesImpl = new StudentServicesImpl();
			int sid= Integer.parseInt(request.getParameter("sid"));
			String name = request.getParameter("sname");
			Double fees = Double.parseDouble(request.getParameter("fees"));

			student.setSid(sid);
			student.setName(name);
			student.setFees(fees);

			try {
				int i = studentServicesImpl.createStudent(student);
				if(i==1){
					request.setAttribute("smsg", "Record Saved Successfully");
					request.getRequestDispatcher("/studentregister.jsp").forward(request, response);

				}else{
					request.setAttribute("tmsg", "Transaction Error");
					request.getRequestDispatcher("/studentregister.jsp").forward(request, response);

				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			try {
				System.out.println("GetALL");
				students = new ArrayList<Student>();
				studentServicesImpl = new StudentServicesImpl();
				students = studentServicesImpl.getAll();
				request.setAttribute("students", students);
				request.getRequestDispatcher("/studentregister.jsp").forward(request, response);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


	}

}
